package com.koomii.myproject.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.koomii.myproject.service.SmsMailLogService;
import com.koomii.myproject.util.RegexUtils;
import com.koomii.myproject.common.MessageBean;
import com.koomii.myproject.dao.SmsMailLogDao;
import com.koomii.myproject.domain.entity.SmsMailLog;

/**
 *
 * SmsMailLogServiceImpl
 *
 * @author 
 *
 */
@Service("smsMailLogService")
public class SmsMailLogServiceImpl  implements SmsMailLogService{
	
	@Autowired
	private SmsMailLogDao smsMailLogDao;
	
	@Override
	public MessageBean validateMobileCode(String mobile, String verifycode) {
		MessageBean msg = new MessageBean();
		if(!RegexUtils.isMobile(mobile)) {
    		msg.setMessage("手机号无效");
    		msg.fireFailed();
    		return msg;
    	} else if(StringUtils.isBlank(verifycode)) {
    		msg.setMessage("验证码不能为空");
    		msg.fireFailed();
    		return msg;
    	} else {
    		SmsMailLog smsLog = smsMailLogDao.findByMobile(mobile);
        	if(smsLog==null || StringUtils.isBlank(smsLog.getText()) || smsLog.getText().indexOf(verifycode)==-1) {
        		msg.setMessage("验证码错误");
        		msg.fireFailed();
        		return msg;
        	} else {
        		long times = (new Date().getTime() - smsLog.getSendTime().getTime()) / 1000;
        		//如果验证码大于80秒则超时
        		if(times>300) {
        			msg.setMessage("验证码已失效,请重新发送");
        			msg.fireFailed();
            		return msg;
        		}
        	}
    	}
		msg.fireSuccess();
		msg.setMessage("验证码正确");
		return msg;
	}
	
	@Override
	public Integer save(SmsMailLog smsMailLog){
		return smsMailLogDao.save(smsMailLog);
	}

	@Override
	public void update(SmsMailLog smsMailLog){
		smsMailLogDao.update(smsMailLog);
	}

	@Override
	public void delete(Integer id){
		smsMailLogDao.delete(id);
	}

	@Override
	public SmsMailLog findById(Integer id){
		return smsMailLogDao.findById(id);
	}

	
}